import api from '../api'
import { htmlDecodeByRegExp } from '../assets/js/utils'
import { loadCompanyInfo, loadProductCategory, loadSwiperSliders } from './mutation-types'

export const state = () => ({
  companyInfo: {
    id: 0,
    companyName: '企业站DEMO',
    tel: '138********',
    address: '广东省深圳市南山区',
    contact: '江**',
    mobile: '12345644564',
    zipCode: '518000',
    email: '410958040@qq.com',
    QQ: '',
    QRCode: '',
    desc: '',
    content: '',
    copyRight: 'MIT Licensed | Copyright © 2019-present 江学美'
  },
  categoryList: [],
  slides: []
})

export const getters = {
  htmlContent(state) {
    return htmlDecodeByRegExp(state.companyInfo.content)
  }
}

export const mutations = {
  [loadCompanyInfo](state, payload) {
    state.companyInfo = Object.assign({}, payload.siteInfo)
  },
  [loadProductCategory](state, payload) {
    state.categoryList = [...payload.cates]
  },
  [loadSwiperSliders](state, payload) {
    state.slides = [...payload.slides]
  }
}

export const actions = {
  async nuxtServerInit({ dispatch }) {
    await Promise.all([
      dispatch(loadCompanyInfo),
      dispatch(loadProductCategory)
    ])
  },
  async [loadCompanyInfo](context) { // 加载企业站的信息存储在state中
    try {
      const siteInfo = await api.siteinfo()
      // console.log('获取企业信息', siteInfo.data)
      if (siteInfo.data.errorCode === 0) {
        context.commit({
          type: loadCompanyInfo,
          siteInfo: siteInfo.data.data
        })
      }
    } catch (error) { // 这里的错误是会显示在Server端
      console.log(error)
    }
  },
  async [loadProductCategory](context) { // 加载产品分类列表
    try {
      const resData = await api.productcate()
      if (resData.data.errorCode === 0) {
        context.commit({
          type: loadProductCategory,
          cates: resData.data.data
        })
      }
    } catch (error) {
      console.log(error)
    }
  }
}
